const app = getApp();
const db = wx.cloud.database().collection("cars");

Page({
  data: {
    equipmentDetail: {},
    markers: [],
    scale: 16,
  },
  onLoad: function (options) {
    const equipmentId = options.id; // Assuming equipment ID is stored in the 'id' field of the page parameters
    this.getEquipmentDetail(equipmentId);
    this.mapCtx = wx.createMapContext("myMap");
  },
  getEquipmentDetail: function (id) {
    db.doc(id).get().then(res => {
      console.log(res.data); // Make sure data is retrieved
      const equipmentDetail = res.data;

      // Set default latitude and longitude to 0 if location2 doesn't exist
      const latitude = equipmentDetail.location2 ? equipmentDetail.location2[1] : 0;
      const longitude = equipmentDetail.location2 ? equipmentDetail.location2[0] : 0;

      // Check if equipmentDetail.equipment exists and is an array before sorting
      if (equipmentDetail.equipment && Array.isArray(equipmentDetail.equipment)) {
        equipmentDetail.equipment.sort((a, b) => {
          const order = {
            "五座小车": 1,
            "七座商务车": 2,
            "货车": 3,
            "发电车": 4,
            "洒水车": 5,
            "其他": 6,
          };
          return order[a.cityText] - order[b.cityText];
        });
      } else {
        console.warn("equipmentDetail.equipment is not defined or not an array");
      }

      const marker = {
        id: 1,
        latitude: latitude,
        longitude: longitude,
        title: equipmentDetail.cname,
      };
      const markers = [marker];
      this.setData({
        equipmentDetail,
        markers
      });
    }).catch(err => {
      console.error(err);
    });
  }
});
